package com.downguys.tool.thread.pool;

import com.downguys.tool.thread.ExecutorFactory;
import com.downguys.tool.thread.NamedPoolThreadFactory;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;

import static com.downguys.tool.thread.ThreadNames.T_EVENT_BUS;

/**
 * @author mingmin.zhou(弄死熊猫)
 * @mail 714387891@qq.com
 * @date 2016/12/30
 */
public class DefaultExecutorFactory implements ExecutorFactory{

    private Executor get(ThreadPoolConfig config) {
        String name = config.getName();
        int corePoolSize = config.getCorePoolSize();
        int maxPoolSize = config.getMaxPoolSize();
        int keepAliveSeconds = config.getKeepAliveSeconds();
        BlockingQueue<Runnable> queue = config.getQueue();

        return new DefaultExecutor(corePoolSize
                , maxPoolSize
                , keepAliveSeconds
                , TimeUnit.SECONDS
                , queue
                , new NamedPoolThreadFactory(name)
                , new DumpThreadRejectedHandler(config));
    }

    @Override
    public Executor get(String name) {

        final ThreadPoolConfig config = ThreadPoolConfig
                .build(T_EVENT_BUS)
                .setCorePoolSize(1)
                .setMaxPoolSize(10)
                .setKeepAliveSeconds(TimeUnit.SECONDS.toSeconds(10))
                .setQueueCapacity(-1);
        return get(config);
    }
}
